﻿/*
 * Copyright © 2025−2026 WEI.ZHOU (Willis) (Chengdu). All rights reserved.
 *
 * THIS SOURCE CODE IS PROPRIETARY AND CONFIDENTIAL.
 * It is the exclusive property of WEI.ZHOU (Willis) and may not be
 * used, copied, distributed, or disclosed outside of WEI.ZHOU (Willis)
 * without express written permission.
 *
 * This code is provided to WEI.ZHOU (Willis) under a limited,
 * non-transferable internal license, and is for use only with the author's
 * approved purposes. No external license is granted or implied.
 *
 * Any unauthorized use, reproduction, or distribution is strictly prohibited
 * and may result in severe civil and criminal penalties.
 */

using Aore.Core.BaseModels;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System.Reflection;

namespace Aore.Core.Extensions;

public static class SwaggerConfigExtensions
{
  /// <summary>
  /// 添加SwaggerGen
  /// </summary>
  /// <param name="builder"></param>
  /// <param name="appXmlName"></param>
  public static void AddSwaggerGen(this IServiceCollection builder, string appXmlName)
  { 
    builder.AddSwaggerGen(option => {
      
      // 注释展示
      var xmlPath = Path.Combine(AppContext.BaseDirectory, appXmlName);
      option.IncludeXmlComments(xmlPath);

      // 支持token传值
      option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
        Description = "JWT授权(数据在请求头中)",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
      });

      //添加安全要求
      option.AddSecurityRequirement(new OpenApiSecurityRequirement
      {
        {
          new OpenApiSecurityScheme
          {
            Reference = new OpenApiReference
            {
              Type = ReferenceType.SecurityScheme,
              Id = "Bearer"
            }
          },
          Array.Empty<string>()
        }
      });

      // 支持版本控制
      foreach (var field in typeof(ApiVersion).GetFields())
      {
        option.SwaggerDoc(field.Name, 
          new OpenApiInfo 
          { 
            Title = $"Aore.WebAPI {field.Name}", 
            Version = field.Name,
            Description = $"Aore.WebAPI {field.Name}版本"
          });
      }
    });
  }

  /// <summary>
  /// 添加SwaggerUI
  /// </summary>
  /// <param name="app"></param>
  public static void AddSwaggerUI(this WebApplication app)
  {
    app.UseSwagger();
    app.UseSwaggerUI(option =>
    {
      foreach (var field in typeof(ApiVersion).GetFields())
      {
        option.SwaggerEndpoint($"/swagger/{field.Name}/swagger.json", $"Aore.WebAPI {field.Name}");
      }
    });
  }
}